package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从请求头中获取登录用户的id
        String userId = request.getHeader("userId");

        //1.1 排除登录请求
        String path = request.getRequestURI().toString();
        if(path.contains("/in")){
            return true;
        }

             //2. 判断是否存在
        if(StringUtils.isEmpty(userId)){
            log.error("当前用户没有登录，请求被WmTokenInterceptor阻止了");
            return false;
        }

        //3. 如果存在则创建WmUser对象设置他的id并存到ThreadLocal中
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));

        WmThreadLocalUtil.add(wmUser);

        return true;
    }

    /**
     * 目标方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清空数据
        WmThreadLocalUtil.remove();
    }
}
